# Python 2.4 compatibility
try:
    import json
except ImportError:
    import simplejson as json
    
from django.core import serializers
from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect
from django.template.loader import get_template
from django.template import RequestContext
from django.views.decorators.csrf import csrf_protect

from models import Paste, PasteForm

def index(request, paste_key=None):
    
    if paste_key is None:
        start_index = int(request.GET.get('start', 0))           
        return render_to_response('paster_index.html',
                                  {'pastes' : Paste.objects.filter(private=False).order_by('-timestamp')[start_index:start_index + 10],})
    else:
        try:
            return render_to_response('paster_index.html',
                                      {'pastes' : [Paste.objects.get(pk=paste_key)],})
        except Paste.DoesNotExist:
            return HttpResponse(status=500)
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_protect

@csrf_protect
def popup(request):
    c = {}
    c.update(csrf(request))
    return render_to_response('paster_popup.html', c)

def raw(request, paste_key=None,):
    
    if paste_key is None:
            return HttpResponse(status=500)
    else:
        try:
            return HttpResponse(content=Paste.objects.get(pk=paste_key).data)
        except Paste.DoesNotExist:
            return HttpResponse(status=500)
                
def download(request, paste_key=None,):
    
    if paste_key is None:
            return HttpResponse(status=500)
    else:
        try:
            paste = Paste.objects.get(pk=paste_key)
            response = HttpResponse(content=paste.data, mimetype="text/plain")

            filename = "paste"
            if len(paste.title) > 0:
                filename = paste.title
                
            response["Content-Disposition"]= "attachment; filename=%s.txt" % (filename)
            return response
        except Paste.DoesNotExist:
            return HttpResponse(status=500)

@csrf_protect
def create(request):
    
    if request.method == "POST":
        form = PasteForm(request.POST)
        if not form.is_valid():
            return HttpResponse(status=500)
        
        paste = form.save()

        if request.is_ajax():
            return HttpResponse('''{"errors":[], "data":%s}''' % serializers.serialize("json", [paste]), 'application/json')

        else:
            return redirect("paster/edit/%s/%s" % (paste.hash, paste.edit_hash))
    else:
        return HttpResponse(get_template('paster_create.html').render(RequestContext(request, {'paste' : PasteForm(),})))

@csrf_protect
def edit(request, paste_key=None, edit_key=None):

    if request.method == "POST":
        form = PasteForm(request.POST)
        if not form.is_valid():
            return HttpResponse(status=500)
        
        if paste_key is not None:
            try:
                paste = Paste.objects.get(hash=paste_key, edit_hash=edit_key)
                paste.title = request.POST.get('title') 
                paste.data = request.POST.get('data')
                paste.save()
                return redirect("paster/edit/%s/%s" % (paste.hash, paste.edit_hash))
            except Paste.DoesNotExist:
                return HttpResponse(status=500)
        else:
                paste = form.save()
                return redirect("paster/edit/%s/%s" % (paste.hash, paste.edit_hash))
    else:
        try:
            paste = Paste.objects.get(hash=paste_key, edit_hash=edit_key)
            return HttpResponse(get_template('paster_create.html').render(RequestContext(request, {
                                                                                                   'paste' : PasteForm(instance=paste),
                                                                                                   'paste_key' : paste.hash,
                                                                                                   'edit_key' : paste.edit_hash,
                                                                                                   })))
        except Paste.DoesNotExist:
            return HttpResponse(status=500)


        